package tech.xiaozai.exam.rest;

import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import tech.xiaozai.common.restful.RestResp;
import tech.xiaozai.exam.bo.MenuBO;
import tech.xiaozai.exam.bo.PermissionBO;
import tech.xiaozai.exam.domain.RolePermissionBean;
import tech.xiaozai.exam.service.PermissionService;

import java.util.List;

/**
 * @author xiaozai
 * @version 1.0
 * @date 2020-09-21 09:33
 */
@RestController
public class PermissionController {

    @Autowired
    private PermissionService permissionService;



    @ApiOperation(value = "获取菜单列表")
    @RequestMapping(value = "/menus",method = RequestMethod.GET)
    public RestResp<List<MenuBO>> getMenus(@RequestAttribute("roleIds") List<String> roleIds){
        return RestResp.ok(permissionService.getMenus(roleIds));
    }

    @PreAuthorize("hasAuthority('url:permission:list')")
    @ApiOperation(value = "获取所有权限")
    @RequestMapping(value = "/permissions", method = RequestMethod.GET)
    public RestResp<List<PermissionBO>> getAllPermissions(){
        return RestResp.ok(permissionService.getAllPermissions());
    }

    @PreAuthorize("hasAuthority('url:permission:update')")
    @ApiOperation(value = "修改权限",notes = "修改权限并返回权限列表")
    @RequestMapping(value = "/permissions",method = RequestMethod.PUT)
    public RestResp<List<PermissionBO>> updatePermission(@RequestBody PermissionBO permission){
        permissionService.updatePermission(permission);
        return RestResp.ok(permissionService.getAllPermissions());
    }


    @ApiOperation(value = "获取所有叶子权限ID")
    @RequestMapping(value = "/permissions/leaf-ids",method = RequestMethod.GET)
    public RestResp<List<Long>> getAllPermissionLeafIds(){
        return RestResp.ok(permissionService.getAllPermissionLeafIds());
    }

    @ApiOperation(value = "获取指定角色的权限ID列表")
    @RequestMapping(value = "/roles/{roleId}/permission-ids", method = RequestMethod.GET)
    public RestResp<List<Long>> getPermissionIdsOfRole(@PathVariable Long roleId){
        return RestResp.ok(permissionService.getPermissionIdsOfRole(roleId));
    }


    @PreAuthorize("hasAuthority('url:role:update')")
    @ApiOperation(value = "更新角色的权限")
    @RequestMapping(value = "/roles/permissions",method = RequestMethod.PUT)
    public RestResp<List<Long>> updatePermissionsOfRole(@RequestBody RolePermissionBean bean){
        permissionService.updatePermissionsOfRole(bean.getRoleId(),bean.getPermissionIds());
        return RestResp.ok(permissionService.getPermissionIdsOfRole(bean.getRoleId()));
    }
}
